package orders;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import exception.InvalidNameException;



/**
 * Represents a publisher. Contains references to all current
 * PurchaseOrders for this Publisher. 
 * @author SJP
 *
 */
public class Publisher implements Serializable{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 5904089626630246622L;

	/**
	 * Publisher name
	 */
	private String name;
	
	/**
	 * PuchaseOrders from this Publisher
	 */
	private Map<String,PurchaseOrder> orders;
	
	/**
	 * Creates a new publisher with the given name.
	 * @param n
	 */
	public Publisher(String n) {
		name = n;
		orders = new HashMap<String,PurchaseOrder>();
	}
	
	/**
	 * @return the name of this publisher.
	 */
	public String toString() {return name;}
	
	/**
	 * @param id the name of the PurchaseOrder
	 * @return the PurchaseOrder
	 */
	public PurchaseOrder getPO(String id) throws InvalidNameException {
		if (orders.containsKey(id))
			return orders.get(id);
		else
			throw new InvalidNameException("Publisher getPO: id \""+id+"\" does not exist.");
	}
	
	public PurchaseOrder addNewPO(String id) throws InvalidNameException{
		if (orders.containsKey(id))
			throw new InvalidNameException("Publisher addPO: id \""+id+"\" already exists.");
		else
			return orders.put(id, new PurchaseOrder(id,this));
	}
	
	private void writeObject(ObjectOutputStream out) throws IOException {
		out.defaultWriteObject();
	}
	
	private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
		in.defaultReadObject();
	}
}
